<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 19-3-18
 * Time: 下午3:36
 */

namespace api\modules\jzg\controllers;


use common\components\jingzhengu\Jzg;
use common\components\tools\Model;
use common\components\tools\Tools;
use common\models\JzgBack5;
use common\models\JzgChargePriceLog;
use common\models\JzgPdfGetLog;
use common\models\JzgPlace9Order;
use common\models\JzgUploadImage;
use wodrow\yii\rest\ApiException;
use wodrow\yii\rest\Controller;

class DefaultController extends Controller
{
    /**
     * 上传图片
     * @desc get/post
     * @param string $image_path 图片链接
     * @return mixed
     * @return array plat_resp
     * @return array model
     */
    public function actionImageUpload($image_path)
    {
        $model = JzgUploadImage::findOne(['source_path' => $image_path]);
        $r = [];
        if (!$model) {
            $model = new JzgUploadImage();
            $model->source_path = $image_path;
            $model->created_at = time();
        }
        $model->updated_at = time();
        if ($model->resp_status != 100){
            $jzg = new Jzg();
            $_r = $jzg->imageUpload($image_path);
            $model->resp_status = (string)$_r['Status'];
            $model->url = $_r['ImageUrl'];
            $r['plat_resp'] = $_r;
            $x = json_encode($_r, JSON_UNESCAPED_UNICODE);
            $model->resp_data = $x;
        }
        if (!$model->save()){
            throw new ApiException(201903181727, "数据保存失败:".Model::getModelError($model));
        }
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 精真估下单
     * @desc get/post
     * @param string $json 示例:{"orderNum":"test01","vin":"1234567890AECKDPL","provinceId":"1","cityId":"101","productType":"1","orderName":"张三","orderPhone":"17091551612","imageList":[{"partCode":282,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":283,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":284,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":285,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":286,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":287,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":288,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":289,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":290,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":431,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":432,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":433,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"},{"partCode":434,"imageUrl":"https://imgv5.jingzhengu.com/group2/M01/0E/EC/t0U453.jpg"}]}
     * @return array model 订单数据
     * @return array plat_resp 平台响应数据
     * @throws
     */
    public function actionPlace9Order($json)
    {
        $data = json_decode($json, true);
        if (\Yii::$app->cache->get("jzg_orderNum_".$data['orderNum'])){
            throw new ApiException(201907151023, "并发错误");
        }else{
            \Yii::$app->cache->set("jzg_orderNum_".$data['orderNum'], $data['orderNum'], 30);
        }
        Tools::log($json, 'jzg_place_order_log');
        $model = JzgPlace9Order::findOne(['order_num' => $data['orderNum']]);
        $r = [];
        if (!$model){
            $model = new JzgPlace9Order();
            $model->order_num = $data['orderNum'];
            $model->created_at = time();
        }
        $model->updated_at = time();
        if ($model->resp_status != 100){
            $vin = trim($data['vin']);
            strtoupper($vin);
            $jzg = new Jzg();
            $model->vin = $vin;
            $model->province_id = $data['provinceId'];
            $model->city_id = $data['cityId'];
            $model->image_list = json_encode($data['imageList'], JSON_UNESCAPED_UNICODE);
            $model->order_name = $data['orderName'];
            $model->order_phone = trim($data['orderPhone']);
            $model->time = time()*1000;
            $model->status = JzgPlace9Order::STATUS_SENDED;
            $data['time'] = $model->time;
            $_r = $jzg->place9Order($data);
            $model->resp_status = (string)$_r['Status'];
            if ($model->resp_status != '100'){
                throw new ApiException(201904121508, json_encode($_r, JSON_UNESCAPED_UNICODE));
            }
            $x = json_encode($_r, JSON_UNESCAPED_UNICODE);
            $model->resp_data = $x;
            $r['plat_resp'] = $_r;
        }
        if (!$model->save()){
            throw new ApiException(201903181727, "数据保存失败:".Model::getModelError($model));
        }
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 获取订单信息
     * @desc get/post
     * @param string $orderNum 订单编号
     * @param int $detailType 明细类型(1：只获取价格 2：获取所有信息)
     * @return array model 订单数据
     * @return array plat_resp 见下面的结果
     * @return String carName 品牌车型
     * @return String recordBrand 品牌型号
     * @return String vin VIN码
     * @return String assessmentDes 鉴定结果
     * @return String assessmentDate 鉴定日期
     * @return String assessmentPriceB2C 评估价格-售车价
     * @return String assessmentPriceC2B 评估价格-收车价
     * @return String maxAssessmentPriceB2C 最高售车价（如果超过此价格，不用再调用7修改价格接口）
     * @return String manufacturerPrice 厂家指导价
     * @return String carLicense 车牌号码
     * @return String engineNum 发动机号
     * @return Int mileage 表显里程
     * @return String productionTime 出厂日期
     * @return String recordDate 登记日期
     * @return String registerCity 注册城市
     * @return String registerCityID 注册城市ID
     * @return String registerProv 注册省份
     * @return String registerProvID 注册省份ID
     * @return String drivingMode 驱动方式
     * @return String carType 车辆类型
     * @return String service 使用性质（营运，非营运等）
     * @return Int seating 额定载客
     * @return String transmissionType 变速器
     * @return String fuel 燃料
     * @return String exhaust 排量
     * @return String color 车身颜色
     * @return String assessmentReportPDF 估值报告pdf下载链接
     * @return String assessmentReportH5 估值报告pc端链接
     * @return String firstMonthResidualB2C 第一月车辆残值率-售车价
     * @return String firstMonthResidualC2B 第一月车辆残值率-收车价
     * @return String secondMonthResidualB2C 第二月车辆残值率-售车价
     * @return String secondMonthResidualC2B 第二月车辆残值率-收车价
     * @return String thirdMonthResidualB2C 第三月车辆残值率-售车价
     * @return String thirdMonthResidualC2B 第三月车辆残值率-收车价
     * @return String videoPath 视频路径
     * @return String imageList 必拍图片(格式为JsonArray)
     * @return String appendImageList 附件图片(格式为JsonArray)
     * @return String appAssessmentReportH5 估值报告app端h5链接
     * @return String makeName 品牌
     * @return String modelName 车系
     * @return String styleName 车型
     * @return Int styleYear 年款
     * @return String manufacturerName 制造商
     * @return String maintenanceRecord 维修保养记录(JsonObject)
     */
    public function actionOrderInfo($orderNum, $detailType)
    {
        $r = [];
        $jzg = new Jzg();
        $resp = $jzg->orderInfo($orderNum, $detailType);
        if ($resp['Status'] != 100){
            throw new ApiException(201903201042, "没有找到订单:".json_encode($resp, JSON_UNESCAPED_UNICODE));
        }
        $model = JzgPlace9Order::findOne(['order_num' => $orderNum]);
        if (!$model){
            throw new ApiException(20190417, "数据库没有找到单子");
            /*$models = JzgPlace9Order::find()->where(['vin' => $resp['Data']['vin']])->asArray()->all();
            $r['models'] = $models;
            return $r;*/
        }
        $model->image_list = json_decode($model->image_list);
        $r['plat_resp'] = $resp;
        $r['model'] = $model->toArray();
        return $r;
    }

    /**
     * 获取订单所有信息
     * @desc get/post
     * @param string $orderNum
     * @return array
     */
    public function actionOrderInfos($orderNum)
    {
        $r = [];
        $jzg = new Jzg();
        $resp1 = $jzg->orderInfo($orderNum, 1);
//        $resp2 = $jzg->orderInfo($orderNum, 2);
        $model = JzgPlace9Order::findOne(['order_num' => $orderNum]);
        $model->image_list = json_decode($model->image_list);
        $r['plat_resp1'] = $resp1;
//        $r['plat_resp2'] = $resp2;
        return $r;
    }

    /**
     * 获取pdf
     * @desc get/post
     * @param string $orderNum
     * @return array
     */
    public function actionGetPdf($orderNum)
    {
        $key = "pdf_url_cache_".$orderNum;
        $url = \Yii::$app->cache->get($key);
        if (!$url){
            $log = new JzgPdfGetLog();
            $log->order_num = $orderNum;
            $jzg = new Jzg();
            $resp2 = $jzg->orderInfo($orderNum, 2);
            if ($resp2['Status']==100 && isset($resp2['Data']['assessmentReportPDF'])){
                $url = $resp2['Data']['assessmentReportPDF'];
                \Yii::$app->cache->set($key, $url, 3600*2);
                $log->resp_url = $url;
                $log->created_at = time();
                if (!$log->save()){
                    throw new ApiException(201904251616, Model::getModelError($log));
                }
            }else{
                throw new ApiException(201904241351, "没有获取到pdf详细信息");
            }
        }
        return [
            'pdf_url' => $url,
        ];
    }

    /**
     * 修改价格
     * @desc get/post
     * @param string $orderNum 订单编号
     * @param string $changePrice 修改价格
     */
    public function actionEditPrice($orderNum, $changePrice)
    {
        $key = "pdf_url_cache_".$orderNum;
        $log = new JzgChargePriceLog();
        $log->order_num = $orderNum;
        $log->charge_price = $changePrice;
        $log->created_at = time();
        $r = [];
        $model = JzgPlace9Order::findOne(['order_num' => $orderNum]);
        if (!$model){
            if (!$log->save()){
                throw new ApiException(201904091032, Model::getModelError($log));
            }
            throw new ApiException(201903191658, "数据库没有找到单子");
        }
        $jzg = new Jzg();
        $resp = $jzg->editPrice($model->order_num, $changePrice);
        /*if (!$model->jzg_order_num){
        }else{
            $resp = $jzg->editPrice($model->jzg_order_num, $changePrice);
        }*/
        $log->resp_status = $resp['Status'];
        if ($resp['Status'] != 100){
            if (!$log->save()){
                throw new ApiException(201904091033, Model::getModelError($log));
            }
            throw new ApiException(201903191659, "修改失败:".$resp['Msg']);
        }
        $model->assessment_price_b2c = $changePrice;
        if (!$model->save()){
            throw new ApiException(201903191100, Model::getModelError($model));
        }
        $r['plat_resp'] = $resp;
        $model->image_list = json_decode($model->image_list);
        $r['model'] = $model->toArray();
        if (!$log->save()){
            throw new ApiException(201904091034, Model::getModelError($log));
        }
//        \Yii::$app->cache->delete($key);
//        $this->actionOrderInfoS($orderNum);
        return $r;
    }

    /**
     * 获取vin订单信息
     * @param string $vin
     * @return array
     * @throws
     */
    public function actionGetVinInfo($vin)
    {
        $orders = JzgPlace9Order::find()->where(['vin' => $vin])->all();
        $_orders = [];
        foreach ($orders as $k => $v){
            $x = $v->toArray();
            $y = [];
            foreach ($v->jzgBack5s as $k1 => $v1){
                $y[] = $v1->toArray();
            }
            $x['backs'] = $y;
            $_orders[] = $x;
        }
        return [
            'orders' => $_orders,
        ];
    }
}